<template>
  <div class="customerBox">
    <div class="title">顾客管理</div>
    <div class="btn">
      <el-input v-model="customerInput" placeholder="请输入顾客姓名" clearable class="input-with-select" @change="searchCustomerName" @input="changeInput">
        <el-button slot="append" type="primary" icon="el-icon-search" @click="searchCustomerName">搜索</el-button>
      </el-input>
      <el-button type="primary" icon="el-icon-plus" @click="addCustomer">新增顾客</el-button>
      <!-- <el-button type="primary" @click="batchDelete" class="batchDelete">批量删除</el-button> -->
      <!-- 弹出框modal -->
      <el-dialog :title="modalTitle" center :visible.sync="customerVisible" width="50%" @close="cancel">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :label-position="'right'" status-icon>
          <el-form-item label="姓名" prop="name" >
            <el-input v-model="ruleForm.name" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model="ruleForm.age" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="ruleForm.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="ruleForm.phone" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="消费额" prop="consumption">
            <el-input v-model="ruleForm.consumption" oninput = "value=value.replace(/[^\d]/g,'')" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="VIP等级" prop="level">
            <el-input v-model="ruleForm.level" style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="注册时间" prop="regTime">
            <el-date-picker
              v-model="ruleForm.regTime"
              type="date"
              placeholder="选择注册日期">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="addSure" >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="dataTable">
      <el-table
        :data="tableData.filter(data => !search || data.level.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%"
        :header-cell-style="{textAlign: 'center'}"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          type="selection"
          width="45"
        />
        <el-table-column
          label="顾客id"
          prop="id"
          width="80">
        </el-table-column>
        <el-table-column
          label="姓名"
          prop="name"
          width="80">
        </el-table-column>
        <el-table-column
          label="性别"
          prop="gender"
          width="80">
        </el-table-column>
        <el-table-column
          label="年龄"
          prop="age"
          width="80">
        </el-table-column>
        <el-table-column
          label="联系方式"
          prop="phone"
          width="120">
        </el-table-column>
        <el-table-column
          label="消费额"
          prop="consumption"
          width="100">
        </el-table-column>
        <el-table-column
          label="VIP等级"
          prop="level"
          width="100"
          :render-header="renderHeaderMethod">
        </el-table-column>
        <el-table-column
          label="注册时间"
          prop="regTime">
        </el-table-column>
        <el-table-column
          align="right">
          <template slot="header" slot-scope="">
            <el-input
              v-model="search"
              size="mini"
              placeholder="输入VIP"/>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="info"
              @click="handleDelete(scope.$index, scope.row)">注销</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="float:right"
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handlerChange"
      />
    </div>
  </div>
</template>


<script>
import interfaceList from '../../utils/interface'
export default {
  name:'customer',
  data(){
    return {
      pageSize:8,
      // page:1,
      total:100,
      currentPage:1,
      search:'',
      customerInput:'',
      tableData:[],
      customerVisible: false,
      status:'',
      modalTitle:'',
      ruleForm: {
        name: '',
        age: '',
        gender: '男',
        phone: '',
        consumption: '',
        level: '',
        regTime: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入顾客姓名', trigger: 'blur' },
          { min: 2, message: '长度在 2个字符以上', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入顾客年龄', trigger: 'blur' },
          { min: 1, max: 2, message: '要求输入1-2个数字', trigger: 'blur' },
        ],
        gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入顾客电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '要求输入11个数字', trigger: 'blur' }
        ],
        consumption: [
          { required: true, message: '请输入顾客消费额', trigger: 'blur' },
        ],
        level: [
          { required: true, message: '请输入顾客VIP等级', trigger: 'blur' },
        ],
        regTime: [
          { required: true, message: '请输入顾客注册时间', trigger: 'blur' },
        ],
      },
    }
  },
  methods:{
    renderHeaderMethod(h, { column, $index }) {
      return h("div", [
      h("span", column.label + "  ", {
        align: "left"
      }),
      h(
        "el-popover",
        {
          props: {
            placement: "top-start",    // 一般 icon 处可添加浮层说明，浮层位置等属性
            width: "300",
            trigger: "hover"
          }
        },
        [
          h("p", "VIP等级规则：消费额为2000即为VIP1，由此每增加2000VIP等级提升一级，消费额达到10000后，再消费10000则提升一级，最高为VIP10", {
            class: "text-align: right; margin: 0"
          }),
          h("i", {                            // 生成 i 标签 ，添加icon 设置 样式，slot 必填
            class: "el-icon-question",
            style: "color:#ccc,margin:18px",
            slot: "reference"
          })
        ]
      )
    ]);
    },
     // 格式化时间
    addZero(num) {
      return num < 10 ? '0' + num : num;
    },
    formatDateTime(date) {
      const time = new Date(Date.parse(date));
      time.setTime(time.setHours(time.getHours() + 8));
      const Y = time.getFullYear() + '-';
      const M = this.addZero(time.getMonth() + 1) + '-';
      const D = this.addZero(time.getDate()) + ' ';
      return Y + M + D;
    },
    getLists(){
      interfaceList.pageGetCustomerLists({
        page:this.currentPage,
        pageSize:this.pageSize
      }).then(res=>{
        // console.log(res)
        if(res.code === 200){
          res.customerLists.forEach(item => {
            item.regTime = this.formatDateTime(item.regTime)
          })
          this.tableData = res.customerLists
          this.total = res.count
        }
      })
    },
    handlerChange(val){
      this.currentPage = val
      if(this.customerInput === ''){
        this.getLists()
      }else{
        this.searchCustomerName()
      }
    },
    // 查询
    changeInput(val){
      // console.log(val)
      this.customerInput = val
      if(val === ''){
        this.getLists()
      }
    },
    searchCustomerName(){
      // console.log(this.customerInput)
      if(this.customerInput === ''){
        this.getLists()
        return
      }
      interfaceList.pageGetCustomerNameLists({
        customerName:this.customerInput,
        page:this.currentPage,
        pageSize:this.pageSize
      }).then(res => {
        console.log(res)
        if(res.code === 200){
          res.customerNameLists.forEach(item => {
            item.regTime = this.formatDateTime(item.regTime)
          })
          this.tableData = res.customerNameLists
          this.total = res.count
        }
      })
    },
    // 添加
    cancel(){
      if(this.status === 'add'){
        this.customerVisible = false
        this.$refs.ruleForm.resetFields()
      }else{
        this.customerVisible = false
      }
    },
    addCustomer(){
      this.status = 'add'
      this.modalTitle = '新增顾客'
      this.ruleForm = {
        name: '',
        age: '',
        gender: '男',
        phone: '',
        consumption: '',
        level: '',
        regTime: '',
      },
      this.customerVisible = true
    },
    addSure(){
      // console.log(this.ruleForm)
      if(this.status === 'add') {
        interfaceList.addCustomer({
          name: this.ruleForm.name,
          age: this.ruleForm.age,
          gender: this.ruleForm.gender,
          phone: this.ruleForm.phone,
          consumption: this.ruleForm.consumption,
          level: this.ruleForm.level,
          regTime: this.formatDateTime(this.ruleForm.regTime)
        }).then(res => {
          // console.log(res)
          if(res.code === 200) {
            this.getLists()
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.$refs.ruleForm.resetFields()
          }else{
            this.$message.error(res.msg)
          }
        })
      }else{
        interfaceList.editCustomer({
          id:this.ruleForm.id,
          name: this.ruleForm.name,
          age: this.ruleForm.age,
          gender: this.ruleForm.gender,
          phone: this.ruleForm.phone,
          consumption: this.ruleForm.consumption,
          level: this.ruleForm.level,
          regTime: this.formatDateTime(this.ruleForm.regTime)
        }).then(res => {
          // console.log(res)
          if(res.code === 200) {
            this.getLists()
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      }
      this.customerVisible = false
    },
    // batchDelete(){
    //   console.log('批量删除')
    // },
    // 编辑
    handleEdit(index, row) {
      // console.log(index, row)
      this.ruleForm.id = row.id
      this.ruleForm.name = row.name
      this.ruleForm.age = row.age
      this.ruleForm.gender = row.gender
      this.ruleForm.phone = row.phone
      this.ruleForm.consumption = row.consumption
      this.ruleForm.level = row.level
      this.ruleForm.regTime = row.regTime
      this.customerVisible = true
      this.status = 'edit'
      this.modalTitle = '编辑顾客'
    },
    handleDelete(index, row) {
      this.$confirm('确定注销此顾客吗?', '提示', {
        confirmButtonText: '确定' ,
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        interfaceList.deleteCustomer({
          id:row.id
        }).then(res =>{
          // console.log(res)
          if(res.code === 200) {
            this.currentPage = 1
            this.getLists()
            this.$message({
              type: 'success',
              message: '注销成功!'
            })
          }else{
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        })
      })
    }
  },
  created(){
    this.getLists()
  }
}
</script>


<style lang="scss" scoped>
.customerBox{
    margin: 10px 0 0 10px;
    .title{
        font-size: 22px;
        font-family: PingFangSC-Regular;
        color: #40404C;
        letter-spacing: 0.35px;
        line-height: 28px;
        border-bottom: 0.5px solid #B9B9B9;
        margin: 32px 0 20px 20px;
    }
    .btn{
        .input-with-select{
            width: 250px;
            height: 10px;
            margin-right: 30px;
        }
        .batchDelete{
            margin-right: 20px;
        }
    }
    .dataTable{
        margin-top: 30px;
    }
    .demo-ruleForm{
      position: relative;
      top: 0;
      left: 50px;
    }
}
</style>